﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Event.NCL;
using CPPEI.Coolzon.Event.UI;
using CPPEI.Coolzon.UI.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.UI.Views
{
    /// <summary>
    /// 打开默认场景的线程
    /// </summary>
    public class OpenDefaultSceneThread
    {
        private bool _isRunning = false;

        private Thread _workThread;

        private static object s_lockObj = new object();

        public static OpenDefaultSceneThread s_instance;
        private Metadata.Solution _solution;
        private ManualResetEvent _manualResetEvent;
        private long _latestTicks = 0;

        private bool HasGettedLastViewState = false;
        private bool HasViewState = false;
        private string ViewStateToken;
        private OpenDefaultSceneThread()
        {
            _manualResetEvent = new ManualResetEvent(false);
        }

        /// <summary>
        /// 启动打开方案的默认场景
        /// </summary>
        /// <param name="solution">方案信息</param>
        /// <param name="onFinishedCallback">打开完成之后的回调</param>
        public static void Start(Metadata.Solution solution)
        {
            if (s_instance == null)
            {
                lock (s_lockObj)
                {
                    s_instance = new OpenDefaultSceneThread();

                    s_instance._solution = solution;
                    Coolzon.Event.NCL.NCLEventBus.Register(s_instance);

                    s_instance._workThread = new Thread(Running);
                    s_instance._workThread.Name = "OpenDefaultSceneThread";
                    s_instance._isRunning = true;
                    s_instance._workThread.Start();
                }
            }
        }

        public static void Stop()
        {
            lock (s_lockObj)
            {
                if (s_instance != null && s_instance._isRunning)
                {
                    s_instance._isRunning = false;
                    s_instance._manualResetEvent.WaitOne();
                }
            }
        }

        private static void Running()
        {
            UIEventBus.PublishAsync(new UIDisableInteractiveEvent("正在切换主备服务器"));
            while((string.IsNullOrWhiteSpace(UIContext.Current.MainServerIP) || UIContext.Current.MainServerPort == 0) && s_instance._isRunning)
            {
                if (DateTime.Now.Ticks - s_instance._latestTicks > TimeSpan.FromSeconds(30).Ticks)
                {
                    UIEventBus.PublishAsync(new UIDisableInteractiveEvent("正在切换主备服务器"));
                    s_instance._latestTicks = DateTime.Now.Ticks;
                    UIEventBus.PublishAsync(new UIEnableInteractiveEvent());
                }
                Thread.Sleep(100);
            }
            while (!s_instance.HasGettedLastViewState && s_instance._isRunning)
            {
                if (DateTime.Now.Ticks - s_instance._latestTicks > TimeSpan.FromSeconds(10).Ticks)
                {
                    UIEventBus.PublishAsync(new UIDisableInteractiveEvent("正在获取视图状态"));
                    Coolzon.Event.NCL.NCLBeginGetViewState @event = new Coolzon.Event.NCL.NCLBeginGetViewState(UIContext.Current.SolutionName, UIContext.Current.MainServerIP, UIContext.Current.MainServerPort);
                    Coolzon.Event.NCL.NCLEventBus.Publish(@event);
                    s_instance._latestTicks = DateTime.Now.Ticks;
                    UIEventBus.PublishAsync(new UIEnableInteractiveEvent());
                }
                Thread.Sleep(100);
            }
            if (s_instance.HasViewState && s_instance._isRunning)
            {
                SyncViewStateThread.Start((RenderView)UIContext.Current.RenderView, s_instance.ViewStateToken);
                UIEventBus.PublishAsync(new UIEnableInteractiveEvent());
            }
            else
            {
                while (s_instance._isRunning)
                {
                    if (DateTime.Now.Ticks - s_instance._latestTicks > TimeSpan.FromSeconds(1).Ticks)
                    {
                        UIEventBus.PublishAsync(new UIDisableInteractiveEvent("正在等待终端加载方案"));
                        Coolzon.Event.NCL.NCLBeginCheckClientStatusEvent @event = new Coolzon.Event.NCL.NCLBeginCheckClientStatusEvent(Service.Contract.ClientStatus.Normal);
                        Coolzon.Event.NCL.NCLEventBus.Publish(@event);
                        s_instance._latestTicks = DateTime.Now.Ticks;
                        UIEventBus.PublishAsync(new UIEnableInteractiveEvent());
                    }
                    Thread.Sleep(100);
                }
            }

            //HB:设置心跳开始同步状态
            HeartbeatThread.SetMode(HeartbeatThreadWorkMode.UploadViewState);
            s_instance._manualResetEvent.Set();
            s_instance._manualResetEvent = null;
            Coolzon.Event.NCL.NCLEventBus.Unregister(s_instance);
            s_instance = null;
        }

        [Subscribe]
        public void OnReceiveNCLEndCheckClientStatusEvent(Coolzon.Event.NCL.NCLEndCheckClientStatusEvent @event)
        {
            if (@event.IsPass)
            {
                lock (s_lockObj)
                {
                    if (s_instance != null && s_instance._isRunning && s_instance.HasGettedLastViewState && !s_instance.HasViewState)
                    {                        // 发送指令
                        Metadata.Scene firstScene = s_instance._solution.Scenes.First();

                        NCLOpenSceneEvent @OpenSceneEvent = new NCLOpenSceneEvent(SwitchMode.Replace, "", firstScene.Name, null);
                        @OpenSceneEvent.State = NCLEventState.Sending;
                        NCLEventBus.PublishAsync(@OpenSceneEvent);

                        UIEventBus.PublishAsync(new UIEnableInteractiveEvent());
                        s_instance._isRunning = false;
                    }
                }
            }
        }

        [Subscribe]
        public void OnReceiveNCLEndGetViewState(Coolzon.Event.NCL.NCLEndGetViewState @event)
        {
            if (s_instance.HasGettedLastViewState)
            {
                return;
            }
            if (@event.HasViewStateToken)
            {
                s_instance.HasViewState = true;
                s_instance.ViewStateToken = @event.ViewStateToken;
                s_instance.HasGettedLastViewState = true;
            }
            else
            {
                s_instance.HasViewState = false;
                s_instance.HasGettedLastViewState = true;
            }
        }
    }
}
